<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>诊断信息</h3>
      <el-form ref="diagnosis" :model="diagnosis" status-icon label-position="left" label-width="100px" style="width: 800px; margin-left:50px;">
        <el-form-item label="诊断编号">
          {{diagnosis.code}}
        </el-form-item>
        <el-form-item label="诊断名称">
          {{ diagnosis.name }} <el-link type="primary" v-permission="['POST /admin/diagnosis/update']" icon="el-icon-edit" @click="handleDiagnosisEdit"></el-link>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标准编码">
              {{diagnosis.standardCode}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别限制">
              <el-tag v-if="diagnosis.genderRestrict == 1">限男性</el-tag>
              <el-tag type="danger" v-else-if="diagnosis.genderRestrict == 2">限女性</el-tag>
              <el-tag type="success" v-else>不限</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div class="op-create">
        <h3>诊断用药</h3>
        <div>
          <el-button type="primary" @click="handleCreate" >添加</el-button>
        </div>
      </div>
      <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column align="left" label="编码" prop="drug.code" width="180"/>
        <el-table-column align="left" label="药品名称" prop="drug.name" />
        <el-table-column align="left" label="规格" prop="drug.spec" width="150"/>
        <el-table-column align="left" label="本位码" prop="drug.standardCode" width="140" />
        <el-table-column align="left" label="批准文号" prop="drug.approvalCode" width="150" />
        <el-table-column align="left" label="性别限制" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.drug.genderRestrict == 1">限男性</el-tag>
            <el-tag type="danger" v-else-if="scope.row.drug.genderRestrict == 2">限女性</el-tag>
            <el-tag type="success" v-else>不限</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="儿童用药" width="80">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.drug.childrenFlag">是</el-tag>
            <el-tag type="success" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="剂量单位" prop="drug.dosageUnit" width="80" />

        <el-table-column align="left" label="生产厂家" prop="drug.factory" />
        <el-table-column align="left" label="权重" prop="weight" sortable width="80"/>

        <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button v-permission="['POST /admin/complaint/diagnosis/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-permission="['POST /admin/complaint/diagnosis/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

      <!-- 添加或修改对话框 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="800px">
        <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 700px; margin-left:50px;">
          <template v-if="dataForm.drug">
            <el-row>
              <el-col :span="24">
                <el-form-item label="药品编号">
                  {{ dataForm.drug.code }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="药品名称">
                  {{ dataForm.drug.name }}
                  <el-link type="primary" icon="el-icon-edit-outline" @click="handleChooseDrug"></el-link>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="药品规格">
                  {{ dataForm.drug.spec }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="本位码">
                  {{ dataForm.drug.standardCode }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="批准文号">
                  {{ dataForm.drug.approvalCode }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="性别限制">
                  <el-tag v-if="dataForm.drug.genderRestrict == 1">限男性</el-tag>
                  <el-tag type="danger" v-else-if="dataForm.drug.genderRestrict == 2">限女性</el-tag>
                  <el-tag type="success" v-else>不限</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="儿童用药">
                  <el-tag type="danger" v-if="dataForm.drug.childrenFlag">是</el-tag>
                  <el-tag type="success" v-else>否</el-tag>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="剂量单位">
                  {{ dataForm.drug.dosageUnit }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生产厂家">
                  {{ dataForm.drug.factory }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="权重" prop="weight">
              <el-input v-model="dataForm.weight" />
            </el-form-item>
          </template>
          <template v-else>
            <el-button type="primary" size="mini" @click="handleChooseDrug">选择药品</el-button>
          </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <template v-if="dataForm.drug">
            <el-button v-if="dialogStatus === 'create'" type="primary" @click="createData">确定</el-button>
            <el-button v-else type="primary" @click="updateData">确定</el-button>
          </template>
        </div>
      </el-dialog>

      <el-dialog title="选择药品" :visible.sync="dialogDrugListVisible" width="1000px">
        <!-- 查询和其他操作 -->
        <div class="filter-container">
          <el-input v-model="listQueryDrug.code" clearable class="filter-item" style="width: 200px;" placeholder="请输入药品编码" />
          <el-input v-model="listQueryDrug.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入药品名称" />
          <el-input v-model="listQueryDrug.standardCode" clearable class="filter-item" style="width: 200px;" placeholder="请输入药品本位码" />
          <el-button v-permission="['GET /admin/drug/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleDrugFilter" >查找</el-button>
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoadingDrug" :data="listDrug" element-loading-text="正在查询中。。。" border fit highlight-current-row>
          <el-table-column align="left" label="药品名称" prop="name" />
          <el-table-column align="left" label="规格" prop="spec" width="150"/>
          <el-table-column align="left" label="性别限制" width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.genderRestrict == 1">限男性</el-tag>
              <el-tag type="danger" v-else-if="scope.row.genderRestrict == 2">限女性</el-tag>
              <el-tag type="success" v-else>不限</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="left" label="儿童用药" width="80">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.childrenFlag">是</el-tag>
              <el-tag type="success" v-else>否</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="left" label="生产厂家" prop="factory" />

          <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="80">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="chooseDrug(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="totalDrug > 0" :total="totalDrug" :page.sync="listQueryDrug.page" :limit.sync="listQueryDrug.limit" @pagination="getDrugList" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { readDiagnosis } from "@/api/diagnosis"
import { deleteDiagnosisDrug, listDiagnosisDrug, updateDiagnosisDrug } from "@/api/diagnosisDrug"
import { listDrug } from "@/api/drug"
import Pagination from "@/components/Pagination"

export default {
  name: "DiagnosisDrug",
  components: { Pagination },
  data() {
    return {
      diagnosis: {
        id: undefined,
        code: '',
        name: '',
        standardCode: '',
        genderRestrict: 0
      },
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        diagnosisId: undefined,
        sort: 'weight',
        order: 'desc',
      },
      dataForm: {
        id: undefined,
        diagnosisId: undefined,
        drugId: undefined,
        drug: undefined,
        weight: 1,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        drugId: [
          { required: true, message: '请选择药品', trigger: 'blur' }
        ],
      },

      listDrug: null,
      totalDrug: 0,
      listLoadingDrug: true,
      listQueryDrug: {
        code: undefined,
        name: undefined,
        standardCode: undefined,
        page: 1,
        limit: 10,
        sort: 'create_time',
        order: 'desc'
      },

      dialogDrugListVisible: false
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.$route.query.id == null) {
        return
      }

      const id = this.$route.query.id
      this.listQuery.diagnosisId = id

      readDiagnosis({id}).then(response => {
        this.diagnosis = response.data.data
        this.getList()
      }).catch()
    },
    getList() {
      this.listLoading = true
      listDiagnosisDrug(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        diagnosisId: undefined,
        drugId: undefined,
        drug: undefined,
        weight: 1,
      }
    },
    handleCreate() {
      this.resetForm()
      this.dataForm.diagnosisId = this.diagnosis.id
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createDiagnosisDrug(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加诊断用药成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateDiagnosisDrug(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新诊断用药成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('删除诊断用药, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDiagnosisDrug(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除诊断用药成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {

      })
    },
    handleDiagnosisEdit() {
      this.$router.push({ path: '/diagnosis/edit', query: { id: this.diagnosis.id }})
    },

    handleChooseDrug() {
      this.dialogDrugListVisible = true
      this.listQueryDrug.page = 1
      this.getDrugList()
    },
    handleDrugFilter() {
      this.listQueryDrug.page = 1
      this.getDrugList()
    },
    getDrugList() {
      this.listLoadingDrug = true
      listDrug(this.listQueryDrug)
        .then(response => {
          this.listDrug = response.data.data.list
          this.totalDrug = response.data.data.total
          this.listLoadingDrug = false
        })
        .catch(() => {
          this.listDrug = []
          this.totalDrug = 0
          this.listLoadingDrug = false
        })
    },
    chooseDrug(row) {
      this.dialogDrugListVisible = false
      this.dataForm.drug = row
      this.dataForm.drugId = row.id
    }
  }
}
</script>

<style scoped>
.el-card {
  margin-bottom: 10px;
}
.filter-container {
  margin-top: 20px;
}
.op-create {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
